require 'sqlite3'
require 'rexml/document'

######################################
#
# These functions setup the database and triggers
# files as the bot is initiallized
#
#######################################

class Squick

  # Tries to create the tables in tablesXML in db.  If they fail, it just
  # moves on (they probably already existed)
  def createTables(db, addons)
    addons.each do |addon|
      file = File.new("#{addon}/tables.xml")
      doc = REXML::Document.new(file)
      doc.each_element("Tables/Table") do |table|
        tableName = table.get_elements("TableName").shift.text
        cmd = "create table #{tableName}("
        table.each_element("Columns/Column") do |col|
          cmd += col.get_elements("ColumnName").shift.text
          cmd += " "
          cmd += col.get_elements("ColumnType").shift.text
          cmd += ", "
        end
        cmd = cmd.chop.chop + ")"
        begin
          puts "Executing: --#{cmd}--"
          db.execute(cmd)
        rescue Exception => e
          puts "\t#{e.message}"
        end
      end
    end
  end

  # Refreshes the whole Addon system
  def loadAddons
    @addons = getAddonsList()               # Get a list of the Addons in use
    createTables(@db, @addons)              # Make sure all the tables are created
    @triggers = loadTriggers(@addons)       # Load up all the triggers from the addons

    @addons.each do |addon|
      load "#{addon}/#{addon}.rb" # TODO How to re-require the changes???
    end
  end

  # Gets a list of which all Addons are availible for loading
  def getAddonsList
    `ls|grep Addon`.split ################## This is BAD, fix it with the legit way!!!!!!!!!!!!!!!!!!!!!
  end

  # Loads the XML file for the triggers and stores in in @triggers
  # for later use
  def loadTriggers(addons)
    triggers = Array.new

    addons.each do |addon|
      file = File.new("#{addon}/triggers.xml")
      triggers << REXML::Document.new(file) 
      file.close
    end

    return triggers
  end

end
